﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using audio.Helper;
using audio.Helper.TcpSocket;
using NAudio.Wave;

namespace audio.Play
{
    public class NetworkPlay
    {
        private Client _client;
        readonly object _lockobject = new object();
        readonly Queue<byte[]> _queue = new Queue<byte[]>();
        private int _accept;
        public event Action<string, string> LogEvent;
        public Action<int, int> ChangeEvent;

        private readonly object _objectLock = new object();
        public void Play(string ip, int port)
        {
            _client = new Client(ip, port, 60);
            _client.ReceiveEvent += _commun_ReceiveEvent;
            if (_client.Connection())
            {
                Thread.Sleep(1000);

                if (_client != null)
                {
                    if (!_playstate)
                    {
                        _playstate = true;
                        _state = true;
                        _client.Send(new byte[] { 01, 02 });




                        //刷新播放
                        //Task.Run(() =>
                        //{
                        //    while (_state)
                        //    {
                        //        Task.Run(() =>
                        //        {
                        //Invoke(new Action(() =>
                        //{
                        //    accept_lbl.Text = @"接受数量:" + _accept;
                        //    play_lbl.Text = @"播放数量:" + _play;
                        //}));

                        //        });
                        //        Thread.Sleep(1000);
                        //    }

                        //});

                        //播放
                        Task.Run(() =>
                        {

                            while (_state)
                            {
                                try
                                {
                                    lock (_objectLock)
                                    {

                                        if (_queue.Count > 0)
                                        {
                                            //Invoke(new Action(() =>
                                            //{
                                            //    accept_lbl.Text = @"接受数量:" + _accept;
                                            //    play_lbl.Text = @"播放数量:" + _play;
                                            //}));
                                            ChangeEvent?.Invoke(_accept, _play);

                                            _play++;
                                            var data = _queue.Dequeue();
                                            /*
                                        Stream readFullyStream = new MemoryStream(data);
                                        Mp3Frame frame = Mp3Frame.LoadFromStream(readFullyStream);
                                        _audioPlay.StreamMp3File(frame);
                                        */

                                            ////网络 wav
                                            _audioPlay.StreamMp3File(data);


                                        }
                                    }
                                }
                                catch (Exception ex)
                                {

                                    LogEvent?.Invoke(ex.Message, "错误");
                                }
                            }
                        });


                    }
                }
            }
            else
            {
                LogEvent?.Invoke("客户端连接错误", "错误");
            }
        }

        readonly Queue<byte[]> _cache = new Queue<byte[]>();
        /// <summary>
        /// 接收
        /// </summary>
        /// <param name="data"></param>
        private void _commun_ReceiveEvent(byte[] data)
        {

            lock (_lockobject)
            {
                _accept++;

                //Mp3Frame frame = Mp3Frame.LoadFromStream(readFullyStream);
                //StreamMp3File(frame);
                //if (data.Length > 2)
                //{ 
                if (data[0] == 0)
                {
                    _queue.Enqueue(data);
                }
                else if (data[0] == 1)
                {
                    byte[] copy = new byte[data.Length - 2];
                    Array.Copy(data, 2, copy, 0, copy.Length);

                    switch (data[1])
                    {
                        //开始
                        case 0:
                            _cache.Enqueue(copy);
                            break;
                        //中间
                        case 1:
                            _cache.Enqueue(copy);
                            break;

                        //结束
                        case 2:
                            // _cache.Enqueue(copy);
                            byte[] playData = new byte[_cache.Count * 1152 + copy.Length];
                            int shifting = 0;//偏移
                            while (_cache.Count > 0)
                            {
                                var temp = _cache.Dequeue();
                                Array.Copy(temp, 0, playData, shifting, temp.Length);
                                shifting += temp.Length;
                            }
                            Array.Copy(copy, 0, playData, shifting, copy.Length);
                            _queue.Enqueue(playData);//播放
                           // ConIntArra(playData);
                            break;

                    }
                }
                //  }
                _client.Send(new byte[] { 01, 02 });
            }


        }
        readonly AudioPlay _audioPlay = new AudioPlay();
        public void ConIntArra(byte[] buffer)
        {
            List<int> it = new List<int>();

            string result = "";
            int i = 0;
            while (i < buffer.Length)
            {
                try
                {
                    //int temp = Convert.ToInt32(buffer[i] << 8 | buffer[i + 1]);
                    //it.Add(temp);
                    //result += "0x" + String.Format("{0:X}", temp) + ",";

                    //int temp = Convert.ToInt32(buffer[i] << 8 | buffer[i + 1]);
                    //it.Add(temp);
                    result += "0x" + string.Format("{0:X}", Convert.ToInt32(buffer[i])) + ",";
                    result += "0x" + string.Format("{0:X}", Convert.ToInt32(buffer[i + 1])) + ",";
                }
                catch (Exception ex)
                {
                    string ss = "";
                }
                i += 2;
            }
            _log.Debug(result);
            //log.Info(@"数量:" + it.Count + "  ", result);
            string s = "";
        }

        readonly ILog _log = new LogInfo("log4net.config", "");
        public bool Stop()
        {
            _state = false;
            return _audioPlay.Stop();
        }

        private int _play;
        private bool _playstate;
        private bool _state;

    }
}
